<?php
    // Created By : Julian Ponce
    // B.S. Computer Science - De La Salle Canlubang
    // September 12, 2011

// Start - Checker for those users who will just go to the page by typing directly in the url.
if ($_POST) {
    // INCLUDES CONFIGURATION VARIABLES FOR DATABASE ACCESS
    include('../includes/siteConfig.php');

    // CONNECT TO DATABASE
    $connect = mysql_connect($hostName,$rootName,$dBasePassword) or die ('Unable to connect!');
    mysql_select_db($dBaseName) or die ('Unable to select database!');
    
    // GET VARIABLES VIA POST METHOD
    $userId = $_POST['userId'];
    
    // QUERY - GETS ALL DOCUMENTS BASED ON DOCUMENT TYPE
    $query = 
        "
            
SELECT MainDocument.mainDocumentId mainDocumentId, Log.documentId documentId, Log.activity activity ,Log.logDateTime, newlog.userId previousUser, Log.userId currentUser
FROM Log, MainDocument, Attachment, (SELECT *
                                     FROM Log a
                                     WHERE a.activity = 'Sent'
                                     AND a.logDateTime = ( SELECT MAX(b.logDateTime)
                                                           FROM Log b
                                                           WHERE a.documentId = b.documentId
                                                           AND b.activity='Sent'
                                                         ) 
                                    ) as newlog
WHERE  MainDocument.mainDocumentId = Attachment.mainDocumentId
       AND Attachment.attachmentId = Log.documentId
       AND MainDocument.action = 'Pending' 
       AND Log.logDateTime = ( SELECT MAX(c.logDateTime)
                                  FROM Log c
                                  WHERE Log.documentId = c.documentId
                                )
       AND Log.activity = 'Pending'
       AND newlog.documentId= Log.documentId
       AND newlog.userId = '$userId'
        ";
    
    $result = mysql_query($query) or die ('Error in query: $query. ' . mysql_error());
    
    // SAVE QUERY RESULTS TO AN ARRAY > $row   
   
    if (mysql_num_rows($result) > 0){
        while ($row = mysql_fetch_array($result)) {
            $jsondata = array();
            $jsondata['mainDocumentId'] = $row['mainDocumentId'];
            $jsondata['documentId'] = $row['documentId'];
            $feed[] = $jsondata;
        }

    echo json_encode($feed);
    }
    else{
        echo json_encode(0);
    }
    mysql_free_result($result);
    mysql_close($connect);
}   // End - Checker for those users who will just go to the page by typing directly in the url.
else {
 echo "You are not authorized to view this page. This incident will be reported immediately.";
}
?>
